<template>
  <div class="user-page">
    <div class="header"></div>

    <!-- 固定顶部居中搜索框 -->
    <div class="fixed-search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索题目或选项"
        clearable
        class="search-input"
      />
    </div>

    <!-- 其他筛选按钮和下拉框 -->
    <div class="flex flex-wrap gap-4 items-center mb-6">
      <el-select
        v-model="selectedDifficulty"
        placeholder="全部难度"
        clearable
        style="width: 460px"
        class="w-40"
      >
        <el-option label="简单" value="简单" />
        <el-option label="中等" value="中等" />
        <el-option label="困难" value="困难" />
      </el-select>

      <el-select
        v-model="selectedSubject"
        placeholder="全部学科"
        clearable
        style="width: 460px"
        class="w-40"
      >
        <el-option
          v-for="subject in subjects"
          :key="subject.questionsSubject"
          :label="subject.questionsSubject"
          :value="subject.questionsSubject"
        />
      </el-select>

      <!-- 重置按钮 -->
      <el-button @click="handleResetFilters">重置</el-button>

      <!-- 新增题目按钮（学生不显示） -->
      <el-button
        type="primary"
        @click="dialogVisible = true"
        v-if="userSystemRole !== 'student'"
      >
        新增题目
      </el-button>

      <!-- 考试管理按钮 -->
      <el-button type="primary" @click="goToManager"> 考试管理中心 </el-button>

      <!-- 返回按钮 -->
      <el-button type="primary" @click="goBack">
        返回
      </el-button>
    </div>

    <!-- 题目列表 -->

    <div class="questions-container">
      <div class="question-item" v-for="q in filteredQuestions" :key="q.id">
        <div class="question-title">{{ q.title }}</div>
        <div class="question-info">难度：{{ q.difficulty }}</div>
        <div class="question-answer">答案：{{ q.answer }}</div>
        <div class="question-actions" v-if="userSystemRole !== 'student'">
          <el-button size="small" type="primary" @click="handleEditQuestion(q)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDeleteQuestion(q.id)"
            >删除</el-button
          >
        </div>
      </div>
    </div>

    <!-- 编辑题目弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑题目" width="500px">
      <el-form :model="editQuestion" label-width="80px">
        <el-form-item label="题目">
          <el-input v-model="editQuestion.title" />
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="editQuestion.answer" />
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="editQuestion.difficulty">
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="editQuestion.subject">
            <el-option
              v-for="s in subjects"
              :key="s.questionsSubject"
              :label="s.questionsSubject"
              :value="s.questionsSubject"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateQuestion">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增题目弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增题目" width="500px">
      <el-form :model="newQuestion" label-width="80px">
        <el-form-item label="题目">
          <el-input v-model="newQuestion.title" />
        </el-form-item>

        <!-- 题型选择 -->
        <el-form-item label="题型">
          <el-select
            v-model="newQuestion.questionsType"
            placeholder="请选择题型"
          >
            <el-option label="单选题" :value="0" />
            <el-option label="解答题" :value="1" />
          </el-select>
        </el-form-item>

        <!-- 选项输入框，仅单选题显示 -->
        <template v-if="newQuestion.questionsType === 0">
          <el-form-item label="选项A">
            <el-input v-model="newQuestion.options[0]" />
          </el-form-item>
          <el-form-item label="选项B">
            <el-input v-model="newQuestion.options[1]" />
          </el-form-item>
          <el-form-item label="选项C">
            <el-input v-model="newQuestion.options[2]" />
          </el-form-item>
          <el-form-item label="选项D">
            <el-input v-model="newQuestion.options[3]" />
          </el-form-item>
        </template>
        <template v-if="newQuestion.questionsType === 1">
          <el-form-item label="答案">
            <el-input v-model="newQuestion.answer" />
          </el-form-item>
        </template>

        <el-form-item label="难度">
          <el-select v-model="newQuestion.difficulty">
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>

        <el-form-item label="学科">
          <el-select v-model="newQuestion.subject">
            <el-option
              v-for="s in subjects"
              :key="s.questionsSubject"
              :label="s.questionsSubject"
              :value="s.questionsSubject"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateQuestion">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getQuestions,
  deleteQuestion,
  getSubjects,
  createQuestion,
  updateQuestion,
} from "../api/Practice.js";
import { useRouter } from "vue-router";

const router = useRouter();

const goToManager = () => {
  router.push("/api/manage/manages");
};

const questions = ref([]);
const subjects = ref([]);

const selectedSubject = ref("");
const selectedDifficulty = ref("");
const searchKeyword = ref("");

const dialogVisible = ref(false);
const editDialogVisible = ref(false);

const goBack = () => {
  router.back(); // 返回上一级页面
  // 或者跳转到首页： router.push("/api/redirect");
};

const newQuestion = ref({
  id: 0,
  title: "",
  questionsType: 0,
  options: ["", "", "", ""],
  answer: "",
  difficulty: "",
  subject: "",
});

const editQuestion = ref({
  title: "",
  answer: "",
  difficulty: "",
  subject: "",
});

// 过滤后的题目列表
const filteredQuestions = computed(() => {
  const keyword = searchKeyword.value.toLowerCase();
  return questions.value.filter((q) => {
    const matchSubject =
      !selectedSubject.value || q.subject === selectedSubject.value;
    const matchDifficulty =
      !selectedDifficulty.value || q.difficulty === selectedDifficulty.value;
    const matchKeyword =
      q.title?.toLowerCase().includes(keyword) ||
      q.options?.some?.((opt) => opt?.toLowerCase?.().includes(keyword));
    return matchSubject && matchDifficulty && matchKeyword;
  });
});

// 加载题目
const loadQuestionList = async () => {
  try {
    const res = await getQuestions();
    questions.value = Array.isArray(res.data) ? res.data : [res.data];
  } catch {
    ElMessage.error("获取题目失败");
  }
};

// 加载学科
const loadSubjectList = async () => {
  try {
    const res = await getSubjects();
    subjects.value = res.data || [];
  } catch {
    ElMessage.error("获取学科失败");
  }
};

// 重置筛选
const handleResetFilters = () => {
  selectedSubject.value = "";
  selectedDifficulty.value = "";
  searchKeyword.value = "";
};

// 新增题目
const handleCreateQuestion = async () => {
  try {
    const payload = {
      id: 0,
      title: newQuestion.value.title,
      questionsType: newQuestion.value.questionsType,
      options: newQuestion.value.options.map((content, index) => ({
        questionsId: 0,
        options: String.fromCharCode(65 + index),
        content,
      })),
      answer: newQuestion.value.answer,
      difficulty: newQuestion.value.difficulty,
      subject: newQuestion.value.subject,
    };
    await createQuestion(payload);
    ElMessage.success("新增成功");
    dialogVisible.value = false;
    await loadQuestionList();
    newQuestion.value = {
      id: 0,
      title: "",
      questionsType: 0,
      options: ["", "", "", ""],
      answer: "",
      difficulty: "",
      subject: "",
    };
  } catch {
    ElMessage.error("新增失败");
  }
};

// 编辑题目
const handleEditQuestion = (q) => {
  editQuestion.value = { ...q };
  editDialogVisible.value = true;
};

// 更新题目
const handleUpdateQuestion = async () => {
  try {
    await updateQuestion(editQuestion.value);
    ElMessage.success("修改成功");
    editDialogVisible.value = false;
    await loadQuestionList();
  } catch {
    ElMessage.error("修改失败");
  }
};

// 删除题目
const handleDeleteQuestion = async (id) => {
  try {
    await deleteQuestion(id);
    questions.value = questions.value.filter((q) => q.id !== id);
    ElMessage.success("删除成功");
  } catch {
    ElMessage.error("删除失败");
  }
};

onMounted(() => {
  loadSubjectList();
  loadQuestionList();
});
</script>


<style scoped>
.user-page {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(
      rgba(255, 255, 255, 0.85),
      rgba(255, 255, 255, 0.85)
    ),
    url("../assets/gao.png") center/cover no-repeat;
  background-attachment: fixed;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 固定顶部居中搜索栏 */
.fixed-search-bar {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 12px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}
.fixed-search-bar:hover {
  transform: translateX(-50%) translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.search-input {
  width: 400px;
  max-width: 90vw;
}

/* 筛选按钮和操作按钮 */
.flex {
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  margin: 80px 0 16px;
}

.el-button {
  transition: transform 0.2s;
}
.el-button:hover {
  transform: translateY(-2px);
}

/* 题目列表：3列网格布局 */
.questions-container {
  width: 100%;
  max-width: 1500px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px 24px;
  margin-bottom: 40px;
}

.question-item {
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}
.question-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

.question-title {
  font-weight: 600;
  font-size: 18px;
  color: #333;
  margin-bottom: 6px;
  user-select: text;
}

.question-info {
  color: #666;
  margin-bottom: 4px;
  user-select: text;
}

.question-answer {
  color: #3aaf5d;
  font-weight: 600;
  margin-bottom: 12px;
  user-select: text;
}

.question-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 编辑/新增弹窗样式优化 */
.el-dialog {
  border-radius: 12px;
}
.el-form-item {
  margin-bottom: 12px;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .questions-container {
    grid-template-columns: 1fr;
  }
  .fixed-search-bar {
    width: 90%;
  }
  .flex {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
